from fake_useragent import UserAgent
import requests
import json
import pymysql

url = 'http://matchweb.sports.qq.com/kbs/list?from=NBA_PC&columnId=100000&startTime=2018-04-21&endTime=2018-04-27&_=1526885340764'
ua = UserAgent()
headers={}
headers['User-Agent'] = ua.random
#一次get获取(str)
r = requests.get(url,headers = headers).text
data = json.loads(r)['data']
# print(data)
for dataList in data.values():
    for dict in dataList:
        a = [dict.get('startTime'),dict.get('rightName'),dict.get('rightGoal'),dict.get('leftName'),dict.get('leftGoal')]
        conn = pymysql.connect(host="localhost", user="root",
                             password="root", db="nba", port=3306,charset = 'utf8')
        # 使用cursor()方法获取操作游标
        cur = conn.cursor()
        #编写sql语句
        sql = "INSERT INTO schedule(startTime,rightName,rightGoal,leftName,leftGoal) VALUES (%s,%s,%s,%s,%s)"
        effect = cur.execute(sql,a)
        conn.commit()
print('添加数据库成功！')
# 关闭游标
cur.close()
# 关闭连接
conn.close()